#ifndef _MODBUS_MASTER_H_
#define _MODBUS_MASTER_H_

#include "main.h"
#include "bsp_port.h"

typedef unsigned short modbus_t;
typedef unsigned char modbus_BYTE_t;

typedef enum
{
    MB_OK = 0,
    MB_FUNCODE_ERR = 0x01,
    MB_DATA_ADDR_ERR = 2,
    MB_DATA_VALUE_ERR = 3,
    MB_UNIT_ERROR = 4,
    MB_CODE_ERROR = 5,
    MB_BUSY_ERROR = 6,

} MB_ERROR_TYPEDEF;

typedef struct __PACKED
{
    modbus_BYTE_t mb_slave_id;
    modbus_BYTE_t mb_function;
} Modbus_base_Typedef;

// 读取错误标志
typedef struct __PACKED
{
    Modbus_base_Typedef mb_base;
    modbus_BYTE_t mb_err_code;
    modbus_t mb_crc;
} MB_ERR_Typedef;

// 读取多路寄存器指令
typedef struct __PACKED
{
    Modbus_base_Typedef mb_base;
    modbus_BYTE_t mb_datalen;
    modbus_t mb_data[120];
    modbus_t mb_crc;
} MB_read_reg_RX_Typedef;

// 写单路寄存器指令
typedef struct __PACKED
{
    Modbus_base_Typedef mb_base;
    modbus_t mb_start_addr;
    modbus_t mb_data;
    modbus_t mb_crc;
} MB_write_reg_RX_Typedef;

// 写多路寄存器指令
typedef struct __PACKED
{
    Modbus_base_Typedef mb_base;
    modbus_t mb_start_addr;
    modbus_t mb_word_datalen;
    modbus_t mb_crc;
} MB_write_regs_RX_Typedef;

#ifndef MB_DMA
#define MB_putchar(data, Len) bsp_USART_DMA_SendBytes(data, Len)
#else
#define MB_Dma_Send(data, size) UART_DMASend(USART2, data, size)
#endif
#define MB_delay(ms) LL_mDelay(ms)

#define REG16SWAP(data) (((data << 8) & 0xFF00) | ((data >> 8) & 0x00FF))
#define REG32SWAP(data) (((data << 24) & 0xFF000000) | ((data << 8) & 0x00FF0000) | ((data >> 8) & 0x0000FF00) | ((data >> 24) & 0x000000FF))

MB_ERROR_TYPEDEF mb_read_reg(modbus_BYTE_t Slave_Id, modbus_t start_reg_addr, modbus_t datalen, modbus_t *data);

MB_ERROR_TYPEDEF mb_write_single_reg(modbus_BYTE_t Slave_Id, modbus_t start_reg_addr, modbus_t data);

MB_ERROR_TYPEDEF mb_write_multi_reg(modbus_BYTE_t Slave_Id, modbus_t start_reg_addr, modbus_t datalen, modbus_t *data);

#endif
